import { ReactiveProperty } from './../../../../scripts/libs/rxjs/cc3/ReactiveProperty';
import { _decorator, Component, Node, Label, Button } from 'cc';
import { BaseView } from '../../../../scripts/libs/rxjs/cc3/BaseView';
import { EditorGlass } from './EditorGlass';
import { instantiate } from 'cc';
import { Sprite } from 'cc';
import { Color } from 'cc';
import { Colors } from '../../game/basic';
import { BindButton } from '../../../../scripts/libs/rxjs/cc3/BindButton';
import { EditorStageView } from './EditorStageView';
import { nc } from '../../../../scripts/libs/rxjs/NotificationCenter';
const { ccclass, property } = _decorator;

@ccclass('EditorGlassExplorerItem')
export class EditorGlassExplorerItem extends BaseView {

    editorStageView: EditorStageView = null;

    editorGlass = ReactiveProperty.Create<EditorGlass>(null);

    @property(Node)
    itemPrefabNode: Node = null;

    @property(Node)
    container: Node = null;

    @property(Label)
    glassIdLabel: Label = null;

    @property(Label)
    layerLabel: Label = null;

    @property(Button)
    selfButton: Button = null;

    @property(Node)
    focusNode: Node = null;

    willBind(): void {
        this.itemPrefabNode.removeFromParent();
    }

    useObserves() {
        return [
            this.editorGlass.subscribe(this.refresh.bind(this)),
            BindButton(this.selfButton).subscribe(this.selfButtonClicked.bind(this)),
            nc.subscribe('glass_inspector_change', this.refreshFocus.bind(this)),
        ];
    }

    onDestroyView(): void {
        this.itemPrefabNode.destroy();
    }

    refresh() {
        this.container.destroyAllChildren();
        if (this.editorGlass.value != null) {
            if (this.editorGlass.value.nails.value != null) {
                for (let i = 0; i < this.editorGlass.value.nails.value.length; i++) {
                    let nail = this.editorGlass.value.nails.value[i];
                    let itemNode = instantiate(this.itemPrefabNode);
                    itemNode.getComponent(Sprite).color = Colors[nail];
                    this.container.addChild(itemNode);
                }
            }
            this.glassIdLabel.string = `${this.editorGlass.value.glassId.value}#`;
            this.layerLabel.string = `L${this.editorGlass.value.layer.value}`;
        }
        this.refreshFocus();
    }

    refreshFocus() {
        this.focusNode.active = this.editorStageView.glassInspectorMap.has(this.editorGlass.value?.glassId.value);
    }

    selfButtonClicked() {
        if (this.editorGlass.value != null) {
            this.editorStageView.tryOpenGlassInspector(this.editorGlass.value.glassId.value);
        }
    }

}

